<script setup>
import { ref, onMounted } from 'vue';
import { warnUnitcount } from '@T2/service/api.ts';
import * as echarts from 'echarts';
import dayjs from 'dayjs';

const props = defineProps({
  unit: {
    type: Array,
    required: true,
  }
});

const onlyRef = ref(null);
let myChart = null;
onMounted(() => {
  myChart = echarts.init(onlyRef.value);
  option.series = {};
  loadUnitsData();
});

const getWarnUnitcount = () => {
  return new Promise((resolve, reject) => {
    warnUnitcount({
      method: 'get',
      params: {
        create_time__range: dayjs().format('YYYY') + '-01-01 00:00:00,' +  dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
    }).then(res => {
      resolve(res || []);
    }).catch(err => {
      reject(err);
    })
  })
}

const maxNameWidth = ref(0);
const loadUnitsData = async () => {
  const warnUnitcount = await getWarnUnitcount();
  const oriList = props.unit.map(unit => {
    return { name: unit.name, value: warnUnitcount.find(i => i.unit_id === unit.id)?.count || 0 };
  }).sort(function (a, b) { return b.value - a.value });
  // const oriList = [
  //   { name: '站点1', value: 15 },
  //   { name: '站点2', value: 40 },
  // ].sort(function (a, b) { return b.value - a.value });
  const others = oriList.slice(7);
  const warns = oriList.slice(0, 7);
  warns.push({ name: '其他', value: others.reduce((sum, item) => sum + item.value, 0) });
  maxNameWidth.value = calculateMaxNameWidth(warns.map(item => item.name), '12px sans-serif')
  let datas = warns;
  option.legend.data = warns.map(i => i.name);
  option.legend.textStyle.rich.a.width = maxNameWidth.value;
  option.series = {
    type: 'pie',
    data: datas,
    radius: '55%',
    center: ['30%', '50%'],
    labelLine: {
      show: false,
    },
    label: {
      show: false,
    },
    animationType: 'scale',
    animationEasing: 'elasticOut',
    animationDelay: function (idx) {
      return Math.random() * 200;
    },
  };
  myChart.setOption(option);
}
const option = {
  animation: true,										  	  //是否开启动画
  backgroundColor: 'rgba(0, 18, 24, 0)',    //无背景颜色
  color: ['#59D9CF', '#46DC8A', '#FFD765', '#FFB672', '#FF8F83', '#FFAAEC', '#B47EFF', '#42B5F4'],
  series: {},                               //系列
  tooltip: {
    trigger: 'item',
  },
  grid: {
    containLabel: true,                 //为true表示外边 距离 包含刻度标签在内的整个图表
    bottom: 30,                         //网格离容器底部距离
    right: 24,                          //网格离容器右侧距离
    left: 12,                           //网格离容器左侧距离
    top: 30,                            //网格离容器顶部距离
  },
  legend: {
    orient: 'vertical',
    right: '40px',
    top:'center',
    itemGap: 12,
    itemWidth: 8,
    itemHeight: 8,
    icon: 'circle',
    formatter: function(name) {
      // 获取图例对应的数据项
      const item = option.series.data.find(dataItem => dataItem.name === name);
      return `{a|${name}}{b|${item ? item.value : 0}}`;
    },
    textStyle: {
      rich: {
        a: {
          fontFamily: 'sans-serif',
          color: 'rgba(0,0,0,0.6)',
          padding: [0, 20, 0, 0],
          fontSize: 12,
        },
        b: {
          color: 'rgba(0,0,0,0.9)',// 值的颜色
          fontSize: 12,
        }
      }
    },
  },
}
const calculateMaxNameWidth = (names, font) => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  context.font = font;

  let maxWidth = 0;
  names.forEach(name => {
    const width = context.measureText(name).width;
    if (width > maxWidth) {
      maxWidth = width;
    }
  });
  return maxWidth;
}
</script>

<template>
  <div ref="onlyRef" />
</template>

<style lang="scss" scoped>
div {
  width: 100%;
  height: 100%;
}
</style>